package com.gmics.unifiq.menu;

import java.util.ArrayList;
import java.util.HashMap;

import com.gmics.android.R;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.controller.GooglePlace;
import com.gmics.unifiq.controller.UserFunctions;
import com.gmics.unifiq.entity.CheckIn;
import com.gmics.unifiq.entity.Event;
import com.gmics.unifiq.entity.OpenEvent;
import com.gmics.unifiq.entity.Place;
import com.gmics.unifiq.entity.PlaceDetails;
import com.gmics.unifiq.entity.User;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LoyaltyPoints extends Activity {
	private ProgressDialog pDialog = null;
	private GoogleMap drawMap;
	private final LatLng SINGAPORE = new LatLng(1.368123, 103.798981);
	ArrayList<Integer> eventIDArr = new ArrayList<Integer>(), oeIDArr = new ArrayList<Integer>();
	private EntityController controller = new EntityController();
	private GooglePlace googlePlace = new GooglePlace();
	private ArrayList<PlaceDetails> locationArr = new ArrayList<PlaceDetails>();
	private int locationIcon = R.drawable.map_pin;
	private TextView loyaltyPointsTV;
	private int oeTotalPoints, eventTotalPoints;
	private static int oePoints = 10, eventPoints = 5;
	private ArrayList<OpenEvent> oeArr = new ArrayList<OpenEvent>();
	private ImageView avatarIcon;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loyalty_points_layout);
		
		new LoadMap().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
    class LoadMap extends AsyncTask<String, String, String> {
    	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoyaltyPoints.this);
            pDialog.setMessage("Loading map...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {
    		UserFunctions uf = new UserFunctions();
    		HashMap<String, String> user = uf.getUser(LoyaltyPoints.this);
    		User tempUser = controller.retrieveUser(user.get("uid"));
    		int userID = tempUser.getId();
    		
        	ArrayList<CheckIn> checkInArr = controller.retrieveCheckIn(userID);
        	
        	for (int i = 0; i < checkInArr.size(); i++){
        		if (checkInArr.get(i).getOpenEventID() == 0){
        			eventIDArr.add(checkInArr.get(i).getEventID());
        		}
        		else if (checkInArr.get(i).getEventID() == 0){
        			oeIDArr.add(checkInArr.get(i).getOpenEventID());
        		}
        	}
        	
        	ArrayList<Event> eventArr = new ArrayList<Event>();
        	
        	eventArr = controller.retrieveEventByID(eventIDArr);
        	oeArr = controller.retrieveOpenEventByID(oeIDArr);
        	
    		try {
    		   	for (int a = 0; a < eventArr.size(); a++){
    		   		locationArr.add(googlePlace.getPlaceDetails(eventArr.get(a).getLocationReference()));
    		   	}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	
    		
            return null;
        }
 
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                	Bitmap bm = (Bitmap) getIntent().getParcelableExtra("avatarBitmap");
                	avatarIcon = (ImageView) findViewById(R.id.avatar_icon);
                	avatarIcon.setImageBitmap(bm);
                	
                	drawMap = ((MapFragment) getFragmentManager().findFragmentById(
            				R.id.draw_map)).getMap();
            		drawMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            		drawMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SINGAPORE, 11.5f));

            		
            		for (int b = 0; b < oeArr.size(); b++){
            			String location = oeArr.get(b).getLocation();
            			
                		if (location.equals("NUS")){
                			LatLng area = new LatLng(1.3223561, 103.8189167);
                    		drawMap.addMarker(new MarkerOptions().position(area)
                    				.title("National University of Singapore").snippet("21 Lower Kent Ridge Road 119077")
                    				.icon(BitmapDescriptorFactory.fromResource(locationIcon)));
                		}
                		else if (location.equals("NTU")){
                			LatLng area = new LatLng(1.346305, 103.681150);
                    		drawMap.addMarker(new MarkerOptions().position(area)
                    				.title("Nanyang Technological University").snippet("Nanyang Ave 639798")
                    				.icon(BitmapDescriptorFactory.fromResource(locationIcon)));
                		}
                		else if (location.equals("SMU")){
                			LatLng area = new LatLng(1.297564, 103.849399);
                    		drawMap.addMarker(new MarkerOptions().position(area)
                    				.title("Singapore Management University").snippet("81 Victoria St  188065")
                    				.icon(BitmapDescriptorFactory.fromResource(locationIcon)));
                		}
                		else if (location.equals("SIM")){
                			LatLng area = new LatLng(1.328807, 103.775847);
                    		drawMap.addMarker(new MarkerOptions().position(area)
                    				.title("Singapore Institute of Management").snippet("461 Clementi Rd 599491")
                    				.icon(BitmapDescriptorFactory.fromResource(locationIcon)));
                		}
                	
            		}
            		
            		for (int i = 0; i < locationArr.size(); i++){
            			LatLng area = new LatLng(locationArr.get(i).result.geometry.location.lat, locationArr.get(i).result.geometry.location.lng);
                		drawMap.addMarker(new MarkerOptions().position(area)
                				.title(locationArr.get(i).result.name).snippet(locationArr.get(i).result.formatted_address)
                				.icon(BitmapDescriptorFactory.fromResource(locationIcon)));
            		}

            		loyaltyPointsTV = (TextView) findViewById(R.id.loyalty_points_tv);
            		ImageView loyaltyPointsSpeech = (ImageView) findViewById(R.id.loyalty_points_speech);
            		loyaltyPointsSpeech.setVisibility(View.VISIBLE);
            		
                	oeTotalPoints = oeIDArr.size() * oePoints;
                	eventTotalPoints = eventIDArr.size() * eventPoints;
                	
                	loyaltyPointsTV.setText(Html.fromHtml("You have achieved <big>" + String.valueOf(oeTotalPoints) + "</big> loyalty points for attending "
                	+ String.valueOf(oeIDArr.size()) + " university events and <big>" + String.valueOf(eventTotalPoints) + "</big> loyalty points for attending "
                	+ String.valueOf(eventIDArr.size()) + " group events for a grand total of <big>" + String.valueOf(oeTotalPoints + eventTotalPoints) + "</big> loyalty points!"));
            		 
            		/*drawMap.setOnMarkerClickListener(new OnMarkerClickListener() {
            		public boolean onMarkerClick(Marker marker) {
            			
            			if (markerClicked) {

            				if (polyline != null) {
            					polyline.remove();
            					polyline = null;
            				}

            				rectOptions.add(marker.getPosition());
            				rectOptions.color(Color.RED);
            				polyline = drawMap.addPolyline(rectOptions);
            			} else {
            				if (polyline != null) {
            					polyline.remove();
            					polyline = null;
            				}

            				rectOptions = new PolylineOptions().add(marker.getPosition());
            				markerClicked = true;
            			}

            		    return true;
            		}
            		});*/
            		
						}
            			
            		});
            		
            		
                }
            
        }
    
 
}

